const Router = require('koa-router')
const Redis = require('koa-redis')
const nodeMailer = require('nodemailer')
const passport = require('./utils/passport')
const axios = require('./utils/axios')
const Email = require('../dbs/config')
const userModel = require('../dbs/models/user')

let redisStore = new Redis().client
let router = new Router({
    prefix: '/user'
})
// 验证码,先判断是否频繁请求
router.post('/verify', async (ctx, next) => {
    let username = ctx.request.body.username
    let saveExpire = await redisStore.hget(`nodemail:${username}`, 'expire')
    global.console.log(username, saveExpire)
    if (saveExpire && new Date().getTime() - saveExpire < 0) {
        ctx.body = {
            code: -1,
            msg: 'get code too quick,1 min 1 time...'
        }
        return false
    }
    let transporter = nodeMailer.createTransport({
        host: Email.smtp.host,
        port: Email.smtp.port,
        secure: false,
        auth: {
            user: Email.smtp.user,
            pass: Email.smtp.pass
        }
    })
    let receiver = {
        code: Email.smtp.code(),
        expire: Email.smtp.expire(),
        email: ctx.request.body.email,
        user: ctx.request.body.username
    }
    let mailContent = {
        from: `认证邮箱<${Email.smtp.user}>`,
        to: receiver.email,
        subject: '陈大富的个人博客注册码',
        html: `欢迎到访陈大富的个人博客，注册功能的验证码是 ${receiver.code}`
    }
    await transporter.sendMail(mailContent, (err, info) => {
        if (err) {
            ctx.body = {
                code: -1,
                msg: 'email send err...'
            }
        } else {
            redisStore.hmset(`nodemail:${receiver.username}`, 'code', receiver.code(), 'expire', receiver.expire(), 'email', receiver.email)
        }
    })
    ctx.body = {
        code: 0,
        msg: 'code has send,check email and use it in 1 min...'
    }
})
// 注册接口
router.post('/signup', async (ctx) => {
    let { username, password, email, code } = ctx.request.body
    global.console.log(ctx.request.body)
    // 验证 验证码
    if (code) {//是否有验证码
        let saveCode = await redisStore.hget(`nodemail:${username}`, 'code')
        let saveExpire = await redisStore.hget(`nodemail:${username}`, 'expire')
        if (code === saveCode) { //验证码相等
            if (new Date().getTime - saveExpire > 0) {//验证码过期
                ctx.body = {
                    code: -1,
                    msg: 'code timeout,try it again...'
                }
                return false
            }
        } else {//验证码不相等
            ctx.body = {
                code: -1,
                msg: 'code wrong,try it again...'
            }
        }
    } else {//没有天验证码
        ctx.body = {
            code: -1,
            msg: 'code is necessary...'
        }
    }
    // 验证用户 先查再验证
    let user = await userModel.find({
        username
    })
    if (user && user.length) {
        ctx.body = {
            code: -1,
            msg: 'user alerdy exist...'
        }
        return false
    }
    // 通过校验，先写库，成功之后自动登录操作
    let createUser = await userModel.create({
        username, password, email
    })
    if (createUser) {
        let res = await axios.post('/user/signin', {
            username, password
        })
        if (res.data && res.data.code == 0) {
            ctx.body = {
                code: 0,
                msg: 'auto login success...',
                user: res.data.user
            }
        } else {
            ctx.body = {
                code: -1,
                msg: 'auto login err...',
            }
        }
    } else {
        ctx.body = {
            code: -1,
            msg: 'register err...',
        }
    }
})

// 登录接口
router.post('/signin', async (ctx, next) => {
    return passport.authenticate('local', function (err, user, info, status) {
        if (err) {
            ctx.body = {
                code: -1,
                msg: 'err',
                user
            }
        } else {
            if (user) {
                ctx.body = {
                    code: 0,
                    msg: 'login success...'
                }
                return ctx.login(user)
            } else {
                ctx.body = {
                    code: 1,
                    msg: info
                }
            }
        }
    })(ctx, next)
})
// 退出登录,先退出再检查是否在登陆状态
router.get('/exit', async (ctx, next) => {
    await ctx.logout()
    if (!ctx.isAuthenticated()) {
        ctx.body = {
            code: 0,
            msg: 'exit success...'
        }
    } else {
        ctx.body = {
            code: -1,
            msg: 'exit err...'
        }
    }
})
// 获取用户名
router.get('/getUser', async (ctx) => {
    if (ctx.isAuthenticated()) {
        let { username, email } = ctx.session.passport.user
        global.console.log(`${ username } --server router /getUser`)
        ctx.body = {
            username,
            email
        }
    } else {
        ctx.body = {
            username: '',
            email: ''
        }
    }
})

module.exports = router